﻿$hostname = "shouchuang"
$get = Invoke-WebRequest -uri http://ipaddress:8081/gethost
$ip = [System.Text.Encoding]::ASCII.GetString($get.Content)
if($ip.Length -gt 15 -or $ip.Length -lt 10 ){
    echo $ip
    exit
}
$newline = "$ip    $hostname"
$content = ""
$hasold = 0
foreach($line in Get-Content C:\Windows\System32\drivers\etc\hosts) {
    if($line -match $hostname){
       $content = $content+$newline+"`n"
       $hasold = 1
    }else{
        $content = $content+$line+"`n"
    }
}
if ($hasold -eq 0){
    $content = $content + $newline
}else{
    $content = $content.Substring(0, $content.Length - 1)
}
$content | Out-File -Encoding ascii C:\Windows\System32\drivers\etc\hosts
echo 已将$newline"写入hosts文件"
cmd /c pause